/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.soap;

import com.entity.Claim;
import com.entity.User;
import java.util.Date;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Administrator
 */
@WebService()
public class DistanceSOAP {

    com.viewer.Viewer viewer;
    boolean run = true;
    int id = 10000;

    public void init() {
        if (run) {
            /*java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
            viewer = new com.viewer.Viewer();
            viewer.setVisible(true);
            }
            });*/
            viewer = new com.viewer.Viewer();
            viewer.setVisible(true);
        /*try {
        Thread.sleep(2000);
        } catch (Exception e) {
        }*/
        }
        run = false;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "login")
    public String login(@WebParam(name = "username") String username, @WebParam(name = "password") String password) {
        if ((username == null) || (password == null)) {
            return "fail";
        } else {
            try {
                EntityManagerFactory emf = Persistence.createEntityManagerFactory("DistanceWebPU");
                EntityManager em = emf.createEntityManager();
                em.getTransaction().begin();
                User u = new User();

                Query q = em.createQuery("SELECT u FROM User u WHERE u.username = :username AND u.password = :password");
                q.setParameter("username", username);
                q.setParameter("password", password);
                u = (User) q.getSingleResult();

                return "success";
            } catch (Exception e) {
                return "fail";
            }

        }
    //return "fail";
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "submitClaim")
    public String submitClaim(@WebParam(name = "startAddress") String startAddress, @WebParam(name = "startGeoPoint") String startGeoPoint, @WebParam(name = "endAddress") String endAddress, @WebParam(name = "endGeoPoint") String endGeoPoint, @WebParam(name = "distance") String distance, @WebParam(name = "routePoints") String routePoints, @WebParam(name = "username") String username, @WebParam(name = "password") String password) {
        init();
        //TODO write your implementation code here:
        if (startAddress != null) {
            System.out.println("StartAddress: " + startAddress);
        } else if (startAddress == null) {
            return "invalid";
        }
        if (startGeoPoint != null) {
            System.out.println("StartGeoPoint: " + startGeoPoint);
        } else if (startGeoPoint == null) {
            return "invalid";
        }
        if (endAddress != null) {
            System.out.println("EndAddress: " + endAddress);
        } else if (endAddress == null) {
            return "invalid";
        }
        if (endGeoPoint != null) {
            System.out.println("EndGeoPoint: " + endGeoPoint);
        } else if (endGeoPoint == null) {
            return "invalid";
        }
        if (distance != null) {
            System.out.println("Distance: " + distance);
        } else if (distance == null) {
            return "invalid";
        }
        if (username != null) {
            System.out.println("Username: " + username);
        } else if (username == null) {
            return "invalid";
        }
        if (password != null) {
            System.out.println("Password: " + password);
        } else if (password == null) {
            return "invalid";
        }

        try {
            EntityManagerFactory emf = Persistence.createEntityManagerFactory("DistanceWebPU");
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();

            Claim c = new Claim();
            User u = new User();
            Date date = new Date();
            Query q = em.createQuery("SELECT u FROM User u WHERE u.username = :username AND u.password = :password");
            q.setParameter("username", username);
            q.setParameter("password", password);
            u = (User) q.getSingleResult();

            c.setDateTime(date);
            c.setDistance(distance);
            c.setEndAddress(endAddress);
            c.setEndGeoPoint(endGeoPoint);
            c.setStartAddress(startAddress);
            c.setStartGeoPoint(startGeoPoint);
            c.setUserId(u.getUserId());
            c.setRoutePoints(routePoints);
            c.setClaimId(id);

            em.persist(c);
            em.getTransaction().commit();
            em.getTransaction().begin();

            Query r = em.createQuery("SELECT c FROM Claim c WHERE c.dateTime = :dateTime AND c.userId = :userId");
            r.setParameter("dateTime", date);
            r.setParameter("userId", u.getUserId());
            c = (Claim) r.getSingleResult();
            viewer.updateText(c.getClaimId(), startAddress, startGeoPoint, endAddress, endGeoPoint, distance, username);
            return "Success";
        } catch (Exception e) {
            e.printStackTrace();
        }


        return "Invalid Login";
    //id++;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "claimHistory")
    public String claimHistory(@WebParam(name = "username") String username, @WebParam(name = "password") String password) {
        if ((username == null) || (password == null)) {
            return "Invalid Login";
        } else {
            try {
                EntityManagerFactory emf = Persistence.createEntityManagerFactory("DistanceWebPU");
                EntityManager em = emf.createEntityManager();
                em.getTransaction().begin();
                User u = new User();

                Query q = em.createQuery("SELECT u FROM User u WHERE u.username = :username AND u.password = :password");
                q.setParameter("username", username);
                q.setParameter("password", password);
                u = (User) q.getSingleResult();

                Query r = em.createQuery("SELECT c FROM Claim c WHERE c.userId = :userId ORDER BY c.dateTime DESC");
                r.setParameter("userId", u.getUserId());
                r.setMaxResults(10);
                List claimList = r.getResultList();
                if (claimList.size() > 0) {
                    String returnString = "Success\n";
                    for (Object o : claimList) {
                        Claim claim = (Claim) o;
                        returnString += claim.getClaimId() + " " + claim.getStartAddress() + " to " + claim.getEndAddress() + "\n";
                    }
                    System.out.println(returnString);
                    return returnString;
                } else {
                    return "No previous claims were made by you.";
                }
            } catch (Exception e) {
                return "fail";
            }

        }
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "claimDetail")
    public String claimDetail(@WebParam(name = "username") String username, @WebParam(name = "password") String password, @WebParam(name = "claimId") String claimId) {
        if ((username == null) || (password == null)) {
            return "Invalid Login";
        } else {
            try {
                int intClaimId = Integer.parseInt(claimId);
                EntityManagerFactory emf = Persistence.createEntityManagerFactory("DistanceWebPU");
                EntityManager em = emf.createEntityManager();
                em.getTransaction().begin();
                User u = new User();
                Claim c = new Claim();

                Query q = em.createQuery("SELECT u FROM User u WHERE u.username = :username AND u.password = :password");
                q.setParameter("username", username);
                q.setParameter("password", password);
                u = (User) q.getSingleResult();

                Query r = em.createQuery("SELECT c FROM Claim c WHERE c.userId = :userId AND c.claimId = :claimId");
                r.setParameter("userId", u.getUserId());
                r.setParameter("claimId", intClaimId);
                c = (Claim)r.getSingleResult();

                String returnString = "";
                returnString += "Success\n" + c.getStartAddress() + "\n" + c.getStartGeoPoint() + "\n" + c.getEndAddress() + "\n" + c.getEndGeoPoint() + "\n" + c.getDistance() + "\n" + c.getRoutePoints();
                System.out.println(returnString);
                return returnString;

            } catch (Exception e) {
                System.out.println("fail");
                return "fail";
            }
            //return null;
        }
    }
}
